import sys
sys.path.append("../")

from model.CommonDb import *
from frameworks.utils.RedisUtil import *
import json

class ServersController:
    def __init__(self,args):
        self.args = args
        self.redis = RedisUtil()

    def run(self):
        if self.args["func"] == "getColumns":
            return self.getAllColumns(self.args["fields"],self.args["width"])
        elif self.args["func"] == "getCacheColumns":
            return self.getCacheColumns(self.args["fields"],self.args["width"],self.args["model"])
        elif self.args["func"] == "getMap":
            return self.getMap(self.args["fields"])
        elif self.args["func"] == "getEditMap":
            return self.getEditMap(self.args["fields"])
        elif self.args["func"] == "getAddMap":
            return self.getAddMap(self.args["fields"])
        elif self.args["func"] == "getAllData":
            return self.getAllData(self.args["fields"],self.args["data"])
        elif self.args["func"] == "getData":
            return self.getData(self.args["fields"],self.args["page"],self.args["num"],self.args["orderfield"],self.args["asc"],self.args["where"])
        elif self.args["func"] == "getCacheData":
            return self.getCacheData(self.args["model"],self.args["fields"],self.args["orderfield"],self.args["asc"],self.args["where"])
        elif self.args["func"] == "getRowData":
            return self.getRowData(self.args["fields"], self.args["id"])
        elif self.args["func"] == "update":
            return self.update(self.args["data"])
        elif self.args["func"] == "add":
            return self.add(self.args["data"])
        elif self.args["func"] == "delete":
            return self.delete(self.args["data"])

    def getAllColumns(self,fields,width):
        db = CommonDb(self.args["model"])
        rs = db.getAllColumns(fields)
        columns = []
        for row in rs:
            option = {'field': row["field"], 'title': row["comment"], 'sort': 'true', 'fixed': 'left'}
            columns.append(option)
        columns.append({'fixed': 'right', 'title':'操作', 'width':width, 'align':'center', 'toolbar': '#barDemo'})
        return columns

    def getCacheColumns(self,fields,width,model):
        if model == "day_score":
            rs = [
                {"field": "code", "comment": "代码"},
                {"field": "codename", "comment": "名称"},
                {"field": "score", "comment": "分数"},
                {"field": "zf", "comment": "涨幅"},
                {"field": "money", "comment": "流通市值"},
                {"field": "divtime", "comment": "分时图"},
                {"field": "daykline", "comment": "日线图"}
            ]
        else:
            rs = [
                {"field": "code","comment": "代码"},
                {"field": "codename", "comment": "名称"},
                {"field": "zhangfu", "comment": "涨幅"},
                {"field": "money", "comment": "流通市值"},
                {"field": "industry", "comment": "行业"}
            ]
        columns = []
        for row in rs:
            option = {'field': row["field"], 'title': row["comment"], 'sort': 'true', 'fixed': 'left'}
            columns.append(option)
        return columns

    def update(self,data):
        db = CommonDb(self.args["model"])
        return db.update(data," id="+str(data["id"]))

    def add(self,data):
        db = CommonDb(self.args["model"])
        return db.add(data)

    def delete(self,data):
        db = CommonDb(self.args["model"])
        return db.delete_where(" id="+str(data["id"]))

    def getMap(self,fields):
        db = CommonDb(self.args["model"])
        rs = db.getAllColumns(fields)
        map = {}
        for row in rs:
            map[row["field"]] = {"title":row["comment"],"type":row["type"]}
        return map

    def getEditMap(self,fields):
        db = CommonDb(self.args["model"])
        rs = db.getAllColumns(fields)
        map = {}
        for row in rs:
            if row["field"] not in ["ctime", "mtime"]:
                map[row["field"]] = {"title": row["comment"], "type": row["type"]}
        return map

    def getAddMap(self,fields):
        db = CommonDb(self.args["model"])
        rs = db.getAllColumns(fields)
        map = {}
        for row in rs:
            if row["field"] not in ["id","ctime","mtime"]:
                map[row["field"]] = {"title":row["comment"],"type":row["type"]}
        return map


    def getData(self,fields,page,num,orderfield,asc,wherestr="1"):
        db = CommonDb(self.args["model"])
        fieldstr = ""
        for option in fields:
            fieldstr += option + ","
        if self.args["fields"][0] == "*":
            rs = db.getPageData("*", wherestr, page, num, orderfield, asc)
        else:
            rs = db.getPageData(fieldstr[0:-1], wherestr, page, num, orderfield, asc)
        return rs

    def getCacheData(self,model,fields,orderfield,asc,wherestr="1",):
        if model == "day_score":
            rs = json.loads(self.redis.vget("day_score_cache"))
        else:
            rs = json.loads(self.redis.vget("zhangting_cache"))
        print(rs)
        return rs

    def getAllData(self,fields,where):
        db = CommonDb(self.args["model"])
        fieldstr = ""
        for option in fields:
            fieldstr += option + ","
        if where != "1":
            wherestr = "1"
            for wherekey in where.keys():
                wherestr += " and " + wherekey + "='"+ where[wherekey] +"'"
        else:
            wherestr = "1"
        if self.args["fields"][0] == "*":
            rs = db.getAllData("*", wherestr)
        else:
            rs = db.getAllData(fieldstr[0:-1], wherestr)
        return rs

    def getRowData(self,fields,id):
        db = CommonDb(self.args["model"])
        fieldstr = ""
        if self.args["fields"][0] == "*":
            fields = db.getAllFields()
        for option in fields:
            fieldstr += option + ","
        rs = db.getRowData(fieldstr[0:-1], " id=" + id)
        return rs